/**
 * 预测分析AI服务
 * 基于历史数据和实时数据进行智能预测和分析
 */

'use client'

import { realDataService } from './realData'
import { emergencyService } from './emergencyEvents'
import { API_BASE_URL } from './config'

// 预测结果接口
export interface PredictionResult {
  id: string
  type: 'patient_flow' | 'equipment_failure' | 'department_load' | 'resource_optimization'
  title: string
  description: string
  prediction: any
  confidence: number
  timeframe: '1h' | '4h' | '24h' | '7d' | '30d'
  recommendations: string[]
  alertLevel: 'low' | 'medium' | 'high' | 'critical'
  createdAt: Date
}

// 患者流量预测
export interface PatientFlowPrediction {
  timeSlots: Array<{
    time: string
    expectedPatients: number
    confidence: number
  }>
  peakHours: string[]
  totalExpected: number
  trends: {
    hourly: number[]
    weeklyPattern: number[]
    monthlyTrend: 'increasing' | 'decreasing' | 'stable'
  }
}

// 设备故障预测
export interface EquipmentFailurePrediction {
  equipmentId: string
  name: string
  failureProbability: number
  expectedFailureTime: string
  riskFactors: string[]
  maintenanceRecommendations: string[]
  criticalParts: Array<{
    part: string
    condition: number // 0-100%
    needsReplacement: boolean
  }>
}

// 科室负载预测
export interface DepartmentLoadPrediction {
  departmentId: string
  name: string
  expectedLoad: number // 0-100%
  waitTimeProjection: number // minutes
  staffNeeded: number
  resourceRequirements: {
    beds: number
    equipment: string[]
    specialists: string[]
  }
  bottlenecks: string[]
}

// 资源优化建议
export interface ResourceOptimization {
  category: 'staff' | 'equipment' | 'bed' | 'schedule'
  current: any
  optimized: any
  improvement: number // 百分比改善
  implementation: string[]
  estimatedSavings: number
  riskLevel: 'low' | 'medium' | 'high'
}

class PredictiveAI {
  private historicalData: Map<string, any[]> = new Map()
  private models: Map<string, any> = new Map()
  private predictionCache: Map<string, PredictionResult> = new Map()
  private lastUpdate: Date = new Date()

  constructor() {
    this.initializeModels()
    this.loadHistoricalData()
    
    // 定期更新预测
    setInterval(() => {
      this.updatePredictions()
    }, 300000) // 每5分钟更新一次
  }

  /**
   * 初始化预测模型
   */
  private initializeModels() {
    // 患者流量预测模型（基于时间序列分析）
    this.models.set('patient_flow', {
      type: 'time_series',
      weights: {
        hourOfDay: 0.4,
        dayOfWeek: 0.3,
        seasonality: 0.2,
        historical: 0.1
      },
      accuracy: 0.85
    })

    // 设备故障预测模型（基于维护历史和使用率）
    this.models.set('equipment_failure', {
      type: 'survival_analysis',
      factors: {
        usage_hours: 0.35,
        maintenance_history: 0.25,
        age: 0.2,
        environment: 0.1,
        manufacturer: 0.1
      },
      accuracy: 0.78
    })

    // 科室负载预测模型
    this.models.set('department_load', {
      type: 'regression',
      features: {
        patient_flow: 0.4,
        staff_availability: 0.3,
        equipment_status: 0.2,
        historical_pattern: 0.1
      },
      accuracy: 0.82
    })
  }

  /**
   * 加载历史数据
   */
  private async loadHistoricalData() {
    try {
      // 从API加载历史数据
      const response = await fetch(`${API_BASE_URL}/analytics/historical`, {
        headers: { 'Content-Type': 'application/json' }
      })
      
      if (response.ok) {
        const data = await response.json()
        this.historicalData.set('patient_flow', data.patientFlow || [])
        this.historicalData.set('equipment_status', data.equipmentStatus || [])
        this.historicalData.set('department_load', data.departmentLoad || [])
      } else {
        // 使用模拟历史数据
        this.generateMockHistoricalData()
      }
    } catch (error) {
      console.log('无法加载历史数据，使用模拟数据')
      this.generateMockHistoricalData()
    }
  }

  /**
   * 生成模拟历史数据
   */
  private generateMockHistoricalData() {
    const now = new Date()
    const patientFlowData = []
    const equipmentData = []
    const departmentData = []

    // 生成过去30天的数据
    for (let i = 30; i >= 0; i--) {
      const date = new Date(now.getTime() - i * 24 * 60 * 60 * 1000)
      
      // 患者流量数据（考虑工作日/周末差异）
      const isWeekend = date.getDay() === 0 || date.getDay() === 6
      const baseFlow = isWeekend ? 50 : 80
      const randomVariation = Math.random() * 30 - 15
      
      patientFlowData.push({
        date: date.toISOString(),
        count: Math.max(0, Math.round(baseFlow + randomVariation)),
        hour: date.getHours()
      })

      // 设备状态数据
      equipmentData.push({
        date: date.toISOString(),
        equipment_id: 'eq_001',
        usage_hours: Math.random() * 24,
        maintenance_score: Math.random() * 100,
        failure_indicators: Math.random() * 10
      })

      // 科室负载数据
      departmentData.push({
        date: date.toISOString(),
        department: '内科',
        load: Math.random() * 100,
        wait_time: Math.random() * 60,
        staff_count: 5 + Math.round(Math.random() * 3)
      })
    }

    this.historicalData.set('patient_flow', patientFlowData)
    this.historicalData.set('equipment_status', equipmentData)
    this.historicalData.set('department_load', departmentData)
  }

  /**
   * 预测患者流量
   */
  async predictPatientFlow(timeframe: '1h' | '4h' | '24h' = '24h'): Promise<PatientFlowPrediction> {
    const now = new Date()
    const currentData = realDataService.getAllRealTimeData()
    const historicalFlow = this.historicalData.get('patient_flow') || []

    // 基于历史数据计算模式
    const hourlyPatterns = this.calculateHourlyPatterns(historicalFlow)
    const weeklyPatterns = this.calculateWeeklyPatterns(historicalFlow)

    const timeSlots: Array<{time: string; expectedPatients: number; confidence: number}> = []
    const peakHours: string[] = []

    let totalExpected = 0
    const hoursToPredict = timeframe === '1h' ? 1 : timeframe === '4h' ? 4 : 24

    for (let i = 0; i < hoursToPredict; i++) {
      const futureTime = new Date(now.getTime() + i * 60 * 60 * 1000)
      const hour = futureTime.getHours()
      const dayOfWeek = futureTime.getDay()

      // 基于历史模式计算期望值
      const hourlyMultiplier = hourlyPatterns[hour] || 1
      const weeklyMultiplier = weeklyPatterns[dayOfWeek] || 1
      const baseFlow = currentData.kpis.patientCount?.value || 50

      const expectedPatients = Math.round(baseFlow * hourlyMultiplier * weeklyMultiplier * (0.8 + Math.random() * 0.4))
      const confidence = this.calculateConfidence(historicalFlow, hour, dayOfWeek)

      timeSlots.push({
        time: futureTime.toISOString(),
        expectedPatients,
        confidence
      })

      totalExpected += expectedPatients

      // 检测高峰时段
      if (expectedPatients > baseFlow * 1.2) {
        peakHours.push(`${hour}:00-${hour+1}:00`)
      }
    }

    return {
      timeSlots,
      peakHours,
      totalExpected,
      trends: {
        hourly: Array.from({length: 24}, (_, i) => hourlyPatterns[i] || 0),
        weeklyPattern: Array.from({length: 7}, (_, i) => weeklyPatterns[i] || 0),
        monthlyTrend: this.calculateMonthlyTrend(historicalFlow)
      }
    }
  }

  /**
   * 预测设备故障
   */
  async predictEquipmentFailure(): Promise<EquipmentFailurePrediction[]> {
    const currentData = realDataService.getAllRealTimeData()
    const equipmentHistory = this.historicalData.get('equipment_status') || []
    const predictions: EquipmentFailurePrediction[] = []

    for (const equipment of currentData.equipment) {
      if (equipment.status === 'maintenance') continue

      // 分析设备历史数据
      const equipmentHistoryData = equipmentHistory.filter((h: any) => h.equipment_id === equipment.id)
      
      // 计算故障概率
      const usageHours = this.calculateUsageHours(equipment, equipmentHistoryData)
      const maintenanceScore = this.calculateMaintenanceScore(equipment, equipmentHistoryData)
      const ageScore = this.calculateAgeScore(equipment)

      const failureProbability = this.calculateFailureProbability(usageHours, maintenanceScore, ageScore)

      if (failureProbability > 0.3) { // 只返回故障概率较高的设备
        const expectedFailureTime = this.estimateFailureTime(failureProbability, usageHours)
        
        predictions.push({
          equipmentId: equipment.id,
          name: equipment.name,
          failureProbability,
          expectedFailureTime,
          riskFactors: this.identifyRiskFactors(equipment, usageHours, maintenanceScore, ageScore),
          maintenanceRecommendations: this.generateMaintenanceRecommendations(equipment, failureProbability),
          criticalParts: this.analyzeCriticalParts(equipment, failureProbability)
        })
      }
    }

    return predictions.sort((a, b) => b.failureProbability - a.failureProbability)
  }

  /**
   * 预测科室负载
   */
  async predictDepartmentLoad(): Promise<DepartmentLoadPrediction[]> {
    const currentData = realDataService.getAllRealTimeData()
    const patientFlowPrediction = await this.predictPatientFlow('4h')
    const predictions: DepartmentLoadPrediction[] = []

    for (const department of currentData.departments) {
      const expectedPatientFlow = this.estimateDepartmentPatientFlow(department, patientFlowPrediction)
      const currentStaff = department.staffCount || 5
      const currentBeds = department.bedCount || 10

      const expectedLoad = Math.min(100, (expectedPatientFlow / (currentStaff * 10)) * 100)
      const waitTimeProjection = this.calculateWaitTime(expectedPatientFlow, currentStaff)
      const staffNeeded = Math.ceil(expectedPatientFlow / 10)

      predictions.push({
        departmentId: department.id,
        name: department.name,
        expectedLoad,
        waitTimeProjection,
        staffNeeded,
        resourceRequirements: {
          beds: Math.ceil(expectedPatientFlow * 0.3),
          equipment: this.getRequiredEquipment(department.type, expectedLoad),
          specialists: this.getRequiredSpecialists(department.type, expectedLoad)
        },
        bottlenecks: this.identifyBottlenecks(department, expectedLoad, staffNeeded)
      })
    }

    return predictions.sort((a, b) => b.expectedLoad - a.expectedLoad)
  }

  /**
   * 资源优化建议
   */
  async generateResourceOptimization(): Promise<ResourceOptimization[]> {
    const currentData = realDataService.getAllRealTimeData()
    const departmentPredictions = await this.predictDepartmentLoad()
    const optimizations: ResourceOptimization[] = []

    // 人员调配优化
    const staffOptimization = this.optimizeStaffAllocation(currentData.departments, departmentPredictions)
    if (staffOptimization) optimizations.push(staffOptimization)

    // 设备调配优化
    const equipmentOptimization = this.optimizeEquipmentAllocation(currentData.equipment, departmentPredictions)
    if (equipmentOptimization) optimizations.push(equipmentOptimization)

    // 床位调配优化
    const bedOptimization = this.optimizeBedAllocation(currentData.departments, departmentPredictions)
    if (bedOptimization) optimizations.push(bedOptimization)

    // 排班优化
    const scheduleOptimization = this.optimizeSchedule(departmentPredictions)
    if (scheduleOptimization) optimizations.push(scheduleOptimization)

    return optimizations.sort((a, b) => b.improvement - a.improvement)
  }

  /**
   * 更新所有预测
   */
  async updatePredictions() {
    try {
      const now = new Date()
      
      // 患者流量预测
      const patientFlowResult = await this.predictPatientFlow('24h')
      const patientFlowPrediction: PredictionResult = {
        id: `patient_flow_${now.getTime()}`,
        type: 'patient_flow',
        title: '患者流量预测',
        description: `预计未来24小时总接诊 ${patientFlowResult.totalExpected} 人次`,
        prediction: patientFlowResult,
        confidence: 0.85,
        timeframe: '24h',
        recommendations: this.generateFlowRecommendations(patientFlowResult),
        alertLevel: this.determineFlowAlertLevel(patientFlowResult),
        createdAt: now
      }
      
      this.predictionCache.set('patient_flow', patientFlowPrediction)

      // 设备故障预测
      const equipmentFailures = await this.predictEquipmentFailure()
      if (equipmentFailures.length > 0) {
        const equipmentPrediction: PredictionResult = {
          id: `equipment_${now.getTime()}`,
          type: 'equipment_failure',
          title: '设备故障预警',
          description: `发现 ${equipmentFailures.length} 台设备存在故障风险`,
          prediction: equipmentFailures,
          confidence: 0.78,
          timeframe: '7d',
          recommendations: this.generateEquipmentRecommendations(equipmentFailures),
          alertLevel: this.determineEquipmentAlertLevel(equipmentFailures),
          createdAt: now
        }
        
        this.predictionCache.set('equipment_failure', equipmentPrediction)
      }

      // 科室负载预测
      const departmentLoads = await this.predictDepartmentLoad()
      const departmentPrediction: PredictionResult = {
        id: `department_${now.getTime()}`,
        type: 'department_load',
        title: '科室负载预测',
        description: `${departmentLoads.filter(d => d.expectedLoad > 80).length} 个科室预计高负载`,
        prediction: departmentLoads,
        confidence: 0.82,
        timeframe: '4h',
        recommendations: this.generateLoadRecommendations(departmentLoads),
        alertLevel: this.determineDepartmentAlertLevel(departmentLoads),
        createdAt: now
      }
      
      this.predictionCache.set('department_load', departmentPrediction)

      // 资源优化建议
      const optimizations = await this.generateResourceOptimization()
      if (optimizations.length > 0) {
        const optimizationPrediction: PredictionResult = {
          id: `optimization_${now.getTime()}`,
          type: 'resource_optimization',
          title: '资源优化建议',
          description: `发现 ${optimizations.length} 个优化机会，预计提升效率 ${Math.round(optimizations[0]?.improvement || 0)}%`,
          prediction: optimizations,
          confidence: 0.75,
          timeframe: '24h',
          recommendations: this.generateOptimizationRecommendations(optimizations),
          alertLevel: 'medium',
          createdAt: now
        }
        
        this.predictionCache.set('resource_optimization', optimizationPrediction)
      }

      this.lastUpdate = now
      console.log('预测数据已更新')

    } catch (error) {
      console.error('更新预测失败:', error)
    }
  }

  /**
   * 获取所有预测结果
   */
  getAllPredictions(): PredictionResult[] {
    return Array.from(this.predictionCache.values())
  }

  /**
   * 获取特定类型的预测
   */
  getPrediction(type: PredictionResult['type']): PredictionResult | null {
    return this.predictionCache.get(type) || null
  }

  /**
   * 获取高优先级预警
   */
  getHighPriorityAlerts(): PredictionResult[] {
    return Array.from(this.predictionCache.values())
      .filter(p => p.alertLevel === 'high' || p.alertLevel === 'critical')
      .sort((a, b) => {
        const levelOrder = { critical: 4, high: 3, medium: 2, low: 1 }
        return levelOrder[b.alertLevel] - levelOrder[a.alertLevel]
      })
  }

  // 辅助方法
  private calculateHourlyPatterns(data: any[]): Record<number, number> {
    const patterns: Record<number, number[]> = {}
    
    data.forEach(item => {
      const hour = new Date(item.date).getHours()
      if (!patterns[hour]) patterns[hour] = []
      patterns[hour].push(item.count)
    })

    const averages: Record<number, number> = {}
    Object.keys(patterns).forEach(hour => {
      const h = parseInt(hour)
      const values = patterns[h]
      averages[h] = values.reduce((sum, val) => sum + val, 0) / values.length
    })

    return averages
  }

  private calculateWeeklyPatterns(data: any[]): Record<number, number> {
    const patterns: Record<number, number[]> = {}
    
    data.forEach(item => {
      const day = new Date(item.date).getDay()
      if (!patterns[day]) patterns[day] = []
      patterns[day].push(item.count)
    })

    const averages: Record<number, number> = {}
    Object.keys(patterns).forEach(day => {
      const d = parseInt(day)
      const values = patterns[d]
      averages[d] = values.reduce((sum, val) => sum + val, 0) / values.length
    })

    return averages
  }

  private calculateMonthlyTrend(data: any[]): 'increasing' | 'decreasing' | 'stable' {
    if (data.length < 7) return 'stable'
    
    const recentWeek = data.slice(-7).reduce((sum, item) => sum + item.count, 0)
    const previousWeek = data.slice(-14, -7).reduce((sum, item) => sum + item.count, 0)
    
    const change = (recentWeek - previousWeek) / previousWeek
    
    if (change > 0.1) return 'increasing'
    if (change < -0.1) return 'decreasing'
    return 'stable'
  }

  private calculateConfidence(data: any[], hour: number, dayOfWeek: number): number {
    const relevantData = data.filter(item => {
      const itemDate = new Date(item.date)
      return itemDate.getHours() === hour && itemDate.getDay() === dayOfWeek
    })
    
    if (relevantData.length < 3) return 0.5
    if (relevantData.length < 5) return 0.7
    return 0.9
  }

  private calculateUsageHours(equipment: any, history: any[]): number {
    return history.reduce((total, item) => total + (item.usage_hours || 0), 0)
  }

  private calculateMaintenanceScore(equipment: any, history: any[]): number {
    if (history.length === 0) return 50
    const scores = history.map(item => item.maintenance_score || 50)
    return scores.reduce((sum, score) => sum + score, 0) / scores.length
  }

  private calculateAgeScore(equipment: any): number {
    const installDate = equipment.installDate ? new Date(equipment.installDate) : new Date(Date.now() - 365 * 24 * 60 * 60 * 1000)
    const ageInDays = (Date.now() - installDate.getTime()) / (24 * 60 * 60 * 1000)
    return Math.min(100, (ageInDays / 1825) * 100) // 5年为100%
  }

  private calculateFailureProbability(usageHours: number, maintenanceScore: number, ageScore: number): number {
    const usageWeight = Math.min(1, usageHours / 8760) * 0.35 // 年使用小时数权重
    const maintenanceWeight = (100 - maintenanceScore) / 100 * 0.25
    const ageWeight = ageScore / 100 * 0.2
    const randomFactor = Math.random() * 0.2
    
    return Math.min(1, usageWeight + maintenanceWeight + ageWeight + randomFactor)
  }

  private estimateFailureTime(probability: number, usageHours: number): string {
    const daysToFailure = Math.round((1 - probability) * 365)
    const failureDate = new Date(Date.now() + daysToFailure * 24 * 60 * 60 * 1000)
    return failureDate.toISOString()
  }

  private identifyRiskFactors(equipment: any, usageHours: number, maintenanceScore: number, ageScore: number): string[] {
    const factors: string[] = []
    
    if (usageHours > 6000) factors.push('使用时间过长')
    if (maintenanceScore < 60) factors.push('维护不当')
    if (ageScore > 80) factors.push('设备老化')
    if (equipment.status === 'busy') factors.push('高负载运行')
    
    return factors
  }

  private generateMaintenanceRecommendations(equipment: any, probability: number): string[] {
    const recommendations: string[] = []
    
    if (probability > 0.7) {
      recommendations.push('立即安排全面检修')
      recommendations.push('准备备用设备')
    } else if (probability > 0.5) {
      recommendations.push('安排预防性维护')
      recommendations.push('增加巡检频率')
    } else {
      recommendations.push('按计划维护')
    }
    
    return recommendations
  }

  private analyzeCriticalParts(equipment: any, probability: number): Array<{part: string; condition: number; needsReplacement: boolean}> {
    const parts = ['电机', '传感器', '控制器', '过滤器']
    return parts.map(part => ({
      part,
      condition: Math.round((1 - probability + Math.random() * 0.2) * 100),
      needsReplacement: probability > 0.6 && Math.random() < 0.3
    }))
  }

  private estimateDepartmentPatientFlow(department: any, flowPrediction: PatientFlowPrediction): number {
    const departmentRatio = department.type === '急诊科' ? 0.3 : 
                           department.type === '内科' ? 0.25 : 
                           department.type === '外科' ? 0.2 : 0.15
    return Math.round(flowPrediction.totalExpected * departmentRatio)
  }

  private calculateWaitTime(patientFlow: number, staffCount: number): number {
    const serviceRate = staffCount * 10 // 每名医护人员每小时处理10个患者
    if (serviceRate >= patientFlow) return 5 // 最小等待时间
    return Math.round((patientFlow / serviceRate - 1) * 60) // 超出部分转为等待时间
  }

  private getRequiredEquipment(departmentType: string, load: number): string[] {
    const baseEquipment = ['血压计', '听诊器']
    if (load > 70) {
      baseEquipment.push('心电图机', '检查床')
    }
    if (departmentType === '急诊科') {
      baseEquipment.push('除颤器', '监护仪')
    }
    return baseEquipment
  }

  private getRequiredSpecialists(departmentType: string, load: number): string[] {
    const specialists: string[] = []
    if (load > 80) {
      specialists.push('主治医师')
      if (departmentType === '内科') specialists.push('心内科专家')
      if (departmentType === '外科') specialists.push('外科专家')
    }
    return specialists
  }

  private identifyBottlenecks(department: any, expectedLoad: number, staffNeeded: number): string[] {
    const bottlenecks: string[] = []
    
    if (expectedLoad > 90) bottlenecks.push('人员不足')
    if (staffNeeded > (department.staffCount || 5)) bottlenecks.push('医护人员紧张')
    if (expectedLoad > 80 && (department.bedCount || 10) < staffNeeded * 2) bottlenecks.push('床位不足')
    
    return bottlenecks
  }

  private optimizeStaffAllocation(departments: any[], predictions: DepartmentLoadPrediction[]): ResourceOptimization | null {
    const totalCurrentStaff = departments.reduce((sum, dept) => sum + (dept.staffCount || 5), 0)
    const totalNeededStaff = predictions.reduce((sum, pred) => sum + pred.staffNeeded, 0)
    
    if (totalNeededStaff <= totalCurrentStaff) return null
    
    return {
      category: 'staff',
      current: { total: totalCurrentStaff, distribution: departments.map(d => ({ name: d.name, count: d.staffCount || 5 })) },
      optimized: { total: totalCurrentStaff, distribution: predictions.map(p => ({ name: p.name, count: p.staffNeeded })) },
      improvement: 15,
      implementation: ['调配人员到高负载科室', '启动应急人员调度'],
      estimatedSavings: 50000,
      riskLevel: 'low'
    }
  }

  private optimizeEquipmentAllocation(equipment: any[], predictions: DepartmentLoadPrediction[]): ResourceOptimization | null {
    // 设备优化逻辑
    return null
  }

  private optimizeBedAllocation(departments: any[], predictions: DepartmentLoadPrediction[]): ResourceOptimization | null {
    // 床位优化逻辑
    return null
  }

  private optimizeSchedule(predictions: DepartmentLoadPrediction[]): ResourceOptimization | null {
    // 排班优化逻辑
    return null
  }

  private generateFlowRecommendations(prediction: PatientFlowPrediction): string[] {
    const recommendations: string[] = []
    
    if (prediction.peakHours.length > 0) {
      recommendations.push(`在高峰时段 ${prediction.peakHours.join(', ')} 增加人员配置`)
    }
    
    if (prediction.trends.monthlyTrend === 'increasing') {
      recommendations.push('考虑增加长期人员配置以应对增长趋势')
    }
    
    return recommendations
  }

  private generateEquipmentRecommendations(failures: EquipmentFailurePrediction[]): string[] {
    return failures.slice(0, 3).map(f => `${f.name}: ${f.maintenanceRecommendations[0]}`)
  }

  private generateLoadRecommendations(loads: DepartmentLoadPrediction[]): string[] {
    return loads
      .filter(l => l.expectedLoad > 80)
      .slice(0, 3)
      .map(l => `${l.name}: 建议增加 ${l.staffNeeded - (l.staffNeeded > 5 ? 5 : 3)} 名医护人员`)
  }

  private generateOptimizationRecommendations(optimizations: ResourceOptimization[]): string[] {
    return optimizations.slice(0, 3).map(o => o.implementation[0])
  }

  private determineFlowAlertLevel(prediction: PatientFlowPrediction): 'low' | 'medium' | 'high' | 'critical' {
    if (prediction.peakHours.length > 3) return 'high'
    if (prediction.peakHours.length > 1) return 'medium'
    return 'low'
  }

  private determineEquipmentAlertLevel(failures: EquipmentFailurePrediction[]): 'low' | 'medium' | 'high' | 'critical' {
    if (failures.some(f => f.failureProbability > 0.8)) return 'critical'
    if (failures.some(f => f.failureProbability > 0.6)) return 'high'
    if (failures.length > 0) return 'medium'
    return 'low'
  }

  private determineDepartmentAlertLevel(loads: DepartmentLoadPrediction[]): 'low' | 'medium' | 'high' | 'critical' {
    if (loads.some(l => l.expectedLoad > 95)) return 'critical'
    if (loads.some(l => l.expectedLoad > 85)) return 'high'
    if (loads.some(l => l.expectedLoad > 70)) return 'medium'
    return 'low'
  }
}

// 导出单例实例
export const predictiveAI = new PredictiveAI()

// 导出快捷方法
export const getPredictions = () => predictiveAI.getAllPredictions()
export const getHighPriorityAlerts = () => predictiveAI.getHighPriorityAlerts()
export const updatePredictions = () => predictiveAI.updatePredictions()

export default predictiveAI